package com.xc.ksxt.service;

import com.google.common.base.Optional;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.collect.Lists;
import com.xc.ksxt.entity.PaperCopyEntity;
import com.xc.ksxt.vo.PaperCopyVO;
import com.xc.common.object.PageInfo;
import com.xc.common.tool.BeanAid;
import com.xc.common.tool.Helper;
import com.xc.db.tables.PaperCopy;
import com.xc.db.tables.records.PaperCopyRecord;
import java.util.List;
import java.util.concurrent.ExecutionException;
import org.apache.commons.lang3.StringUtils;
import org.jooq.Condition;
import org.jooq.DSLContext;
import org.jooq.Record;
import org.jooq.Result;
import org.jooq.SelectForUpdateStep;
import org.jooq.SelectSeekStepN;
import org.jooq.SortField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class PaperCopyService {
	@Autowired
	private DSLContext dsl;
	private PaperCopy PAPERCOPYTB = PaperCopy.PAPER_COPY.as("PAPERCOPYTB");
	public PaperCopy getTable() {
		return PAPERCOPYTB;
	}
	public Result<Record> select(Condition whr, PageInfo<PaperCopyEntity> pageInfo, SortField<?>... orderby) {
		SelectSeekStepN<Record> seek = dsl.select().from(PAPERCOPYTB).where(whr).orderBy(orderby);
		Result<Record> result = null;
		if (pageInfo != null) {
			SelectForUpdateStep<Record> su = seek.limit(pageInfo.getLimit()).offset(pageInfo.getBeginNum());
			result = su.fetch();
		} else {
			result = seek.fetch();
		}
		if (pageInfo != null) {
			pageInfo.setResult(result);
			pageInfo.setList(result.into(PaperCopyEntity.class));
		}
		return result;
	}
	public Result<Record> selectVO(Condition whr, PageInfo<PaperCopyVO> pageInfo, SortField<?>... orderby) {
		SelectSeekStepN<Record> seek = dsl.select().from(PAPERCOPYTB).where(whr).orderBy(orderby);
		Result<Record> result = null;
		if (pageInfo != null) {
			SelectForUpdateStep<Record> su = seek.limit(pageInfo.getLimit()).offset(pageInfo.getBeginNum());
			result = su.fetch();
		} else {
			result = seek.fetch();
		}
		if (pageInfo != null) {
			pageInfo.setResult(result);
			pageInfo.setList(result.into(PaperCopyVO.class));
		}
		return result;
	}

	public List<PaperCopyEntity> select(Condition whr, SortField<?>... orderby) {
		Result<Record> result = dsl.select().from(PAPERCOPYTB).where(whr).orderBy(orderby).fetch();
		List<PaperCopyEntity> list = Lists.newArrayList();
		if (result.size() > 0) {
			list = result.into(PaperCopyEntity.class);
		}
		return list;
	}

	public Long count(Condition cond) {
		Long count = dsl.selectCount().from(PAPERCOPYTB).where(cond).fetchOneInto(Long.class);
		return count;
	}

	public Record getRecordById(Long id) {
		Record record = dsl.select().from(PAPERCOPYTB).where(PAPERCOPYTB.ID.eq(id)).fetchOne();
		return record;
	}

	public PaperCopyEntity getEntityById(Long id) {
		Record r = getRecordById(id);
		if(r==null) {
			return null;
		}
		PaperCopyEntity entity = r.into(PaperCopyEntity.class);
		return entity;
	}

	public String update(PaperCopyEntity entity) {
		PaperCopyRecord record = new PaperCopyRecord();
		record.from(entity);
		dsl.executeUpdate(record);
		invalidateCache(entity.getId());
		return entity.getId();
	}

	public String insert(PaperCopyEntity entity) {
		PaperCopyRecord record = new PaperCopyRecord();
        if(StringUtils.isEmpty(entity.getId())) {
        	 String id = Helper.getSnowId() + "";
             entity.setId(id);
        }
        record.from(entity);
        dsl.executeInsert(record);
        invalidateCache(entity.getId());
        return entity.getId();
	}

	public String save(PaperCopyEntity entity) {
		if (entity.getId()==null||entity.getId().isEmpty()) {
			return insert(entity);
		}
		PaperCopyEntity entity2 = getEntityById(Long.valueOf(entity.getId()));
		if(entity2==null) {
			return insert(entity);
		}
		return update(entity);
	}

	public void deleteById(Long id) {
		dsl.delete(PAPERCOPYTB).where(PAPERCOPYTB.ID.eq(id)).execute();
		invalidateCache(id);
	}
	public static LoadingCache<Long, Optional<PaperCopyEntity>> cache = CacheBuilder.newBuilder().maximumSize(500).build(
            new CacheLoader<Long, Optional<PaperCopyEntity>>() {
                public Optional<PaperCopyEntity> load(Long id) {
                	PaperCopyService service = BeanAid.getBean(PaperCopyService.class);
                    PaperCopyEntity user = service.getEntityById(id);
                    return Optional.fromNullable(user);
                }
    });
	public static PaperCopyEntity getFromCaches(Long key) {
        if (key == null) {
            return null;
        }
        try {
            return cache.get(key).orNull();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        return null;
    }
	public static PaperCopyEntity getFromCaches(String key) {
		if (key == null) {
			return null;
		}
		try {
			return cache.get(Long.valueOf(key)).orNull();
		} catch (ExecutionException e) {
			e.printStackTrace();
		}
		return null;
	}
	public static void invalidateCache(String id) {
    	cache.invalidate(Long.valueOf(id));
    }
    public static void invalidateCache(Long id) {
    	cache.invalidate(id);
    }
}
